#ifndef EVENTMANAGER_H
#define EVENTMANAGER_H
#include <list>
#include "dxstdafx.h"

#define FIRE_EVENT(id,event,size) { gEngine->getEventManager().fireEvent(id,event,size); }
#define FIRE_EMPTY_EVENT(id) { gEngine->getEventManager().fireEvent(id); }
typedef uint32 EventID;

namespace ds {

// -------------------------------
//
// -------------------------------
class EventBuffer {

struct Header {
	uint32 index;
	uint32 id;
	size_t size;
};  

public:
	EventBuffer();	
	virtual ~EventBuffer();
	void add(EventID id,const void* p, size_t size);
	void add(EventID id);
	size_t get(void* p, size_t size,uint32 index);
	size_t getByID(void* p, size_t size,EventID id);
	uint32 size() const {
		return m_Total;
	}
	EventID getID(uint32 index);
	uint32 getIndex(EventID id);
	bool containsID(EventID id);
	void reset();
private:
	void write(const void* p, size_t size);
	size_t read(void* p, size_t size,uint32 index);
	char* m_Buffer;
	uint32 m_Index;
	uint32 m_Total;
};

// -------------------------------
// The event handler interface
// -------------------------------
class EventHandler {

public:
    virtual void process(EventBuffer& buffer) = 0;
};

// -------------------------------
//
// -------------------------------
class EventManager {
/*
struct DelayedEvent {

	EventData* event;
	float ttl;
	float timer;

	DelayedEvent(EventData* data,float delay) {
		event = data;
		timer = 0.0f;
		ttl = delay;
	}
};
*/
typedef std::list<EventHandler*> HandlerList;
//typedef std::list<DelayedEvent> DelayedEvents;

public:   
	EventManager() {
		m_Buffer = new EventBuffer();
	}
    ~EventManager() {
		delete m_Buffer;
	}
    void registerEventHandler(EventHandler *handler);
	void fireEvent(EventID id,const void* p, size_t size);
	void fireEvent(EventID id);
	void reset() {
		m_Buffer->reset();
	}
	//void triggerEvent(EventData &event,float delay);
	//void update(float elapsed);	
	void processBuffer();
private:
	EventBuffer* m_Buffer;
    HandlerList handlerList;
	//DelayedEvents m_DelayedEvents;
};

};

#endif // EVENTMANAGER_H
